package github.hotstu.camerax.qrcodec

//import com.google.android.gms.tasks.Task
//import com.google.firebase.ml.vision.FirebaseVision
//import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode
//import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetector
//import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions
//import com.google.firebase.ml.vision.common.FirebaseVisionImage
//import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata
import android.annotation.SuppressLint
import android.util.Log
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.mlkit.vision.barcode.Barcode
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.common.InputImage


/**
 * recognize qrcode using google ML kit
 * @author hglf [hglf](https://github.com/hotstu)
 * @desc 谷歌mlkit解析器
 * @since 6/10/19
 */
class MLQRcodeAnalyzer(
    private val successListener: (List<Barcode>, Int, Int) -> Unit,
    private val fielListener: OnFailureListener
) : ImageAnalysis.Analyzer {

    private val TAG: String = "MLQRcodeAnalyzer"


    //获取解析器
    private val detector = BarcodeScanning.getClient(
        BarcodeScannerOptions.Builder()
            //配置当前扫码格式
            .setBarcodeFormats(
//                二维码
                Barcode.FORMAT_QR_CODE,
//                Barcode.FORMAT_CODE_128,
//                Barcode.FORMAT_CODE_39,
//                Barcode.FORMAT_CODE_93,
//                Barcode.FORMAT_CODABAR,
//                Barcode.FORMAT_DATA_MATRIX,
                //一般的商品码
                Barcode.FORMAT_EAN_13,
//                Barcode.FORMAT_EAN_8,
//                Barcode.FORMAT_ITF,
//                Barcode.FORMAT_UPC_A,
//                Barcode.FORMAT_UPC_E,
//                Barcode.FORMAT_PDF417,
//                Barcode.FORMAT_AZTEC
            )
            .build()
    )


    @SuppressLint("UnsafeExperimentalUsageError")
    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image ?: kotlin.run {
            imageProxy.close()
            return
        }

        val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
        detector.process(image)
            .addOnSuccessListener { barCodes ->
                if (barCodes.size > 0) {
//                    listener.invoke(barCodes[0],imageProxy.width,imageProxy.height)
                    barCodes.forEachIndexed { index, it ->
                        Log.e(
                            TAG,
                            """
                                $index | ${it.rawValue} 
                                |left:${it.boundingBox?.left}|top:${it.boundingBox?.top} |right:${it.boundingBox?.right}|bottom:${it.boundingBox?.bottom}
                                |centerX :${it.boundingBox?.centerX()}| centerY:${it.boundingBox?.centerY()}
                                |format:${Utils.formatType(it.format)}
                            """.trimIndent()
                        )
                    }
                    successListener.invoke(barCodes, imageProxy.width, imageProxy.height)
                    //接收到结果后，就关闭解析
                    detector.close()
                }
            }
            .addOnFailureListener {
                Log.d(TAG, "Error: ${it.message}")
                fielListener.onFailure(Exception(it.message))
            }
            .addOnCompleteListener { imageProxy.close() }

    }
}
